const {
    exec,
    escape
} = require('../../mysql')
const {
    genPassword
} = require('../../../utils/cryp')

const userLogin = (username, password) => {
    username = escape(username)

    // 生成加密密码
    password = genPassword(password)
    // console.log(password)
    password = escape(password)

    const sql = `
        select * from user where username=${username} and password=${password};
    `
    return exec(sql).then(rows => {
        return rows[0] || {}
    })
}

// 获取所有user get 无参数
const getUser = () => {
    const sql = `select username from user;`
    return exec(sql)
}


// 获取管理员 get 无参数
const getUserName = () => {
    const sql = `select userId,username from user where permission = '管理员';`
    return exec(sql)
}

// 获取超级管理员 get 无参数
const getSuperUserName = () => {
    const sql = `select userId,username from user where permission = '超级管理员';`
    return exec(sql)
}

// 删除user post  参数id
const deleteUser = (idAry) => {
    let sql = `delete from user where userId in (${idAry});`
    return exec(sql).then(delData => {
        if (delData.affectedRows > 0) {
            return true
        }
        return false
    })
}

// 升级超级管理员 post 参数id
const upUser = (idAry) => {
    let sql = `update user set permission = '超级管理员' where userId in (${idAry});`
    return exec(sql).then(Data => {
        if (Data.affectedRows > 0) {
            return true
        }
        return false
    })
}

// 降级管理员 post 参数id
const lowUser = (idAry) => {
    let sql = `update user set permission = '管理员' where userId in (${idAry});`
    return exec(sql).then(Data => {
        if (Data.affectedRows > 0) {
            return true
        }
        return false
    })
}

// 新增管理员 post 参数username,password
const addUser = (username, password) => {
    username = escape(username)

    // 生成加密密码
    password = genPassword(password)
    // console.log(password)
    password = escape(password)
    let sql = `insert into user (username,password,permission) values (
        ${username},${password},'管理员'
        );
    `
    // console.log(sql)
    return exec(sql).then(insertData => {
        if (insertData.affectedRows > 0) {
            return true
        }
        return false
    })
}

module.exports = {
    userLogin,
    getUser,
    getUserName,
    getSuperUserName,
    deleteUser,
    upUser,
    lowUser,
    addUser,
}